/**
 * Created by xuan on 15/12/10.
 */
define(function (require) {
    'use strict';
    var angular = require('angular');
    var _ = require('underscore');
    var moment = require('moment');
    var util = require('util');
    var ui = require('ui');
    angular.module('cstAssignApp.controllers', [])
        .controller('cstAssignCtrl', ['$location', '$rootScope', '$scope', 'PAGE_SIZE', 'cstAssignService', 'cstInfoService', 'assignCustomerService', 'recoverCustomerService', 'editCstInfoService',
            function ($location, $rootScope, $scope, PAGE_SIZE, cstAssignService, cstInfoService, assignCustomerService, recoverCustomerService, editCstInfoService) {
                /* 局部变量 start */

                /* 局部变量 end */

                /* $scope变量 start */
                $scope.cstInfoService = cstInfoService;
                $scope.editCstInfoService = editCstInfoService;
                $scope.assignCustomerService = assignCustomerService;
                $scope.recoverCustomerService = recoverCustomerService;
                $scope.tabs = [{
                    text: '跟进中客户',
                    href: '#/following'
                }, {
                    text: '公共客户',
                    href: '#/public_customer'
                }, {
                    text: '垃圾箱',
                    href: '#/dustbin'
                }];
                $scope.curr_tab = _.find($scope.tabs, function (tab) {
                    return $location.path() === tab.href.substring(1);
                });

                var initBaseParams = {
                    page_index: 1,
                    page_size: PAGE_SIZE,
                    sort_field: 'last_date',
                    sort_order: 'desc'
                };
                var initHighParams = {
                    user_id: '',
                    user_id_old: '',
                    last_date_start: '',
                    last_date_end: ''
                };
                $scope.initQueryParams = function () {
                    var copeInitBaseParams = angular.copy(initBaseParams);
                    var copeInitHighParams = angular.copy(initHighParams);
                    var temp = {
                        searchField: 'mobile_tel',
                        searchValue: '',
                        stages: [],
                        followlevels: [],
                        recoverTypes: [0, 0, 0, 0, 0],
                        created_on: {
                            created_on_start: '',
                            created_on_end: '',
                            created_on_custom: false
                        },
                        overdue_day: {
                            overdue_day_start: null,
                            overdue_day_end: null,
                            overdue_day_custom: false
                        }
                    };
                    return angular.extend({}, copeInitBaseParams,copeInitHighParams, temp);
                };
                $scope.resetHighQueryParams = function (oldParams) {
                    var searchField = oldParams.searchField;
                    var searchValue = oldParams.searchValue;
                    var newParams = $scope.initQueryParams();
                    newParams.searchField = searchField;
                    newParams.searchValue = searchValue;
                    return newParams;
                };
                $scope.parseQueryParams = function (params,type) {
                    // base
                    var baseParams = {
                        proj_id: params.proj_id,
                        page_index: params.page_index,
                        page_size: params.page_size,
                        sort_field: params.sort_field,
                        sort_order: params.sort_order
                    };

                    // simple
                    var simpleParams = {};
                    if (params.searchField === 'cst_name') {
                        simpleParams.cst_name = params.searchValue;
                    } else if (params.searchField === 'mobile_tel') {
                        simpleParams.mobile_tel = params.searchValue;
                    }
                    // high
                    var highParams = {};
                    for (var key in initHighParams) {
                        highParams[key] = params[key];
                    }
                    // 逾期天数
                    highParams.overdue_day_start = params.overdue_day.overdue_day_start;
                    highParams.overdue_day_end = params.overdue_day.overdue_day_end;
                    // 客户状态，多个值以逗号分隔，如3,5,6
                    //ret.stage_id = _.map(_.filter(params.stages,function(stage){return stage && stage.checked;}),function(stage){return stage.Value;}).join(',');
                    highParams.stage_id = (function () {
                        var temp_arr = [];
                        _.each(params.stages, function (item, index) {
                            if (item && item.checked) {
                                temp_arr.push($scope.stageList[index].Value);
                            }
                        });
                        return temp_arr.join(',');
                    })();
                    // 意向级别，多个值以逗号分隔，如：2,3,5
                    highParams.follow_level = (function () {
                        var temp_arr = [];
                        _.each(params.followlevels, function (item, index) {
                            if (item && item.checked) {
                                temp_arr.push($scope.followlevelList[index].Value);
                            }
                        });
                        return temp_arr.join(',');
                    })();
                    // 新增日期
                    highParams.created_on_start = params.created_on.created_on_start;
                    highParams.created_on_end = params.created_on.created_on_end;
                    // 回收原因
                    highParams.recover_type = _.filter(params.recoverTypes, function (type) {
                        return type > 0;
                    }).join(',');
                    if(type === 'simple'){
                        return angular.extend({}, baseParams,simpleParams);
                    }else if(type === 'high'){
                        return angular.extend({}, baseParams, highParams);
                    }else{
                        return angular.extend({}, baseParams);
                    }
                };
                $scope.dateDict = (function(){
                    return {
                      yesterday: moment().subtract(1, 'days').format('YYYY-MM-DD'),
                      today: moment().format('YYYY-MM-DD'),
                      monday: moment().day('Monday').format('YYYY-MM-DD'),
                      sunday: moment().day('Sunday').format('YYYY-MM-DD'),
                      monthFirst: moment().date(1).format('YYYY-MM-DD')
                    };
                })();
                $scope.searchType = [{text: '客户姓名', value: 'cst_name'}, {text: '客户电话', value: 'mobile_tel'}];

                /* $scope变量 end */

                /* $scope变量 watch start */
                $scope.$watch('curProjectId', function () {
                    var curProjectId = $scope.curProjectId;
                    if (curProjectId) {
                        $rootScope.currProjectId = curProjectId;

                        $scope.checkHasBindErp(curProjectId);
                        // 更新字典
                        $scope.getStageList(curProjectId);
                        $scope.getFollowlevelList(curProjectId);
                        $scope.getAllSalerList(curProjectId);

                        // 事件通知
                        $scope.$broadcast('changeProjectId', curProjectId);
                    }
                });
                /* $scope变量 watch end */


                /* $scope方法 start */
                $scope.checkHasBindErp = function (proj_id) {
                    cstAssignService
                        .checkHasBindErp({proj_id: proj_id})
                        .then(function (data) {
                            $scope.hasBindErp = data;
                        });
                };
                $scope.getStageList = function (proj_id) {
                    cstAssignService
                        .getStageList({proj_id: proj_id})
                        .then(function (data) {
                            $scope.stageList = data;
                        });
                };
                $scope.getFollowlevelList = function (proj_id) {
                    cstAssignService
                        .getFollowlevelList({proj_id: proj_id})
                        .then(function (data) {
                            $scope.followlevelList = data;
                        });
                };
                $scope.getAllSalerList = function (proj_id) {
                    cstAssignService
                        .getAllSalerList({proj_id: proj_id})
                        .then(function (data) {
                            $scope.allSalerList = _.map(data || [], function (item) {
                                item.text = item.user_name + '(' + item.mobile_tel + ')';
                                return item;
                            });
                        });
                };
                $scope.hasCheck = function (list) {
                    if ($scope.getCheckList(list).length > 0) {
                        return true;
                    } else {
                        util.alert('请选择客户。');
                        return false;
                    }
                };
                $scope.confirmModal = function (total, $dialog, $dialogScope) {
                    if(total === 0){
                        util.alert('没有可分配的客户');
                    }else{
                        util.confirm('确定将查询到' + total + '的客户全部分配吗？', {
                            ok: function () {
                                $dialog.showModal();
                                assignCustomerService.init($scope.curProjectId, $dialogScope);
                            }
                        });
                    }
                    return false;
                };
                $scope.getCheckList = function (list) {
                    list || (list = []);
                    return _.filter(list, {checked: true});
                };
                $scope.checkAllChange = function (list, checkAll) {
                    list || (list = []);
                    if (checkAll) {
                        _.each(list, function (item) {
                            item.checked = true;
                        });
                    } else {
                        _.each(list, function (item) {
                            item.checked = false;
                        });
                    }
                };
                $scope.checkChange = function (list) {
                    list || (list = []);
                    var checkAll = true;
                    _.each(list, function (item) {
                        !item.checked && (checkAll = false);
                    });
                    $scope.$broadcast('checkChange', checkAll);
                };
                //下载模板
                $scope.downloadTemplate = function () {
                    //util.download('/api/index.php?r=ydxs/cst-assign/create-customer-template',{proj_id:$scope.curProjectId});
                    location.href = '/api/index.php?r=ydxs/cst-assign/create-customer-template&proj_id=' + $scope.curProjectId;
                };
                //检查是否需要另开页面下载
                $scope.beforeExportData = function(params){
                    var taskId = false;
                    $.ajax({
                        type: 'GET',
                        async:false,
                        data:$.param(params),
                        contentType:'application/json;charset=UTF-8',
                        url: '/api/index.php?r=ydxs/cst-assign/check-for-async-export&token='+util.getToken(),
                        success: function(res) {
                            if(res.retCode == '0'){
                                if(res.data.needTask){
                                    taskId = res.data.taskId;
                                }
                            }else {
                                util.alert(res.errMsg||'请求失败！');
                            }
                        },
                        error:function(){

                        }
                    });
                    return taskId;
                };
                $scope.export = function (total, query, view_no) {
                    if(total > 0){
                        var data = query;
                        data.view_no = view_no;
                        var task = $scope.beforeExportData(data);
                        if(!task){
                            location.href = '/api/index.php?r=ydxs/cst-assign/export&' + $.param(data);
                        }else{
                            window.open('export_data.html?taskId='+task)
                        }
                    }else{
                        util.alert('没有可导出的数据！');
                    }
                };
                $scope.beforeImportCustomer = function ($dialog, $dialogScope, $data, callback) {
                    $dialogScope.uploadCustomer = function () {
                        if ($dialogScope.uploadStatusNotify && $dialogScope.uploadStatusNotify.status === 'added') {
                            $dialogScope.uploadModel.upload();
                        } else {
                            util.alert('请选择要导入的Excel文件！');
                        }
                    };
                    $dialogScope.onStatusChanged = function($data){
                        if($data.status === 'success'){
                            $dialogScope.filenameWarp = '';
                            var data = $data.response.data;
                            if(data.url){
                                util.alert('<p>'+data.msg+'</p><p><a href="'+data.url+'">错误信息下载</a></p>',{
                                    ok: function(){
                                        callback && callback();
                                        $dialog.close();
                                    }
                                });
                            }else{
                                ui.showSucTip($data.msg);
                                callback && callback();
                                $dialog.close();
                            }
                        }
                    };

                    $dialogScope.$watch('uploadStatusNotify', function (newValue, oldValue) {
                        if (newValue !== oldValue) {
                            if (newValue.status === 'added') {
                                $dialogScope.filenameWarp = newValue.filename;
                            } else if (newValue.status === 'uploading') {
                                ui.showSucTip(newValue.msg);
                            } else if (newValue.status === 'success') {
                                ui.showSucTip(newValue.msg);
                                $dialogScope.filenameWarp = '';
                                callback && callback();
                                $dialog.close();
                            } else if (newValue.status === 'error') {
                                util.alert(newValue.msg);
                                $dialogScope.filenameWarp = '';
                            }
                        }
                    });

                    $data.proj_id = $scope.curProjectId;
                };

                $scope.uploadCustomer = function ($dialog) {
                    $($dialog.node).find('[i-id=cacel]').hide();
                };

                $scope.changeAllStages = function (curProjectId, list, $dialogScope, callback) {
                    cstAssignService.bulkChangeStageId({
                        proj_id: curProjectId,
                        stage_id: $dialogScope.stage_id,
                        opp_ids: _.map(list, 'opp_id')
                    }).then(function () {
                        callback && callback();
                    });
                };


                /* $scope方法 end */

                // init
                cstAssignService.getProjectList({
                    flag: '0',//
                    jointparent: 1//
                }).then(function (data) {
                    $scope.projectList = data;
                });
            }])
        .controller('followingCtrl', ['$location', '$scope', 'cstAssignService', function ($location, $scope, cstAssignService) {
            /* 局部变量 start */
            /* 局部变量 end */

            /* $scope变量 start */
            $scope.followingTabs = [{
                text: '跟进中客户',
                href: '#/following/follow_cus',
                serviceMethod: 'getFollowingList'
            }, {
                text: '逾期客户',
                href: '#/following/overdue_cus',
                serviceMethod: 'getOverDueList'
            },{
                text: '无效客户',
                href: '#/following/invalid_cus',
                serviceMethod: 'getLoseList'
            }];
            $scope.curr_following_tab = _.find($scope.followingTabs, function (tab) {
                return $location.path() === tab.href.substring(1);
            });

            $scope.query = $scope.initQueryParams();

            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$on('changeProjectId', function () {
                $scope.getList();
            });
            $scope.$on('checkChange', function (event, checkAll) {
                $scope.checkAll = checkAll;
            });
            /* $scope变量 watch end */


            /* $scope方法 start */
            $scope.resetGetList = function () {
                $scope.query = $scope.resetHighQueryParams($scope.query);
                $scope.getHighList();
            };
            $scope.getSimpleList = function () {
                $scope.queryType = 'simple';
                $scope.getList();
            };
            $scope.getHighList = function () {
                $scope.queryType = 'high';
                $scope.getList();
            };
            $scope.getList = function (pageIndex) {
                var isPageTrigger = typeof pageIndex !== 'undefined';
                pageIndex || (pageIndex = 1);
                $scope.query.page_index = pageIndex;
                $scope.query.proj_id = $scope.curProjectId;
                cstAssignService[$scope.curr_following_tab.serviceMethod]($scope.parseQueryParams($scope.query,$scope.queryType)).then(function (data) {
                    $scope.tableList = data;

                    // 分页触发时，继续选中标签
                    if($scope.checkCountAll && isPageTrigger){
                        _.map($scope.tableList.list,function(item){
                            item.checked = true;
                        });
                    }else{
                        $scope.checkAll = false;
                        $scope.checkCountAll = false;
                    }
                });
            };

            /* $scope方法 end */

            // init
            if ($scope.curProjectId) {
                $scope.getList();
            }
        }])
        .controller('publicCtrl', ['$scope', 'cstAssignService','progressService', function ($scope, cstAssignService,progressService) {
            /* 局部变量 start */

            /* 局部变量 end */

            /* $scope变量 start */
            $scope.loading = true;

            $scope.query = $scope.initQueryParams();

            $scope.query.sort_field = 'recover_time';

            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$on('changeProjectId', function () {
                $scope.getList();
            });
            $scope.$on('checkChange', function (event, checkAll) {
                $scope.checkAll = checkAll;
            });
            /* $scope变量 watch end */


            /* $scope方法 start */
            $scope.resetGetList = function () {
                $scope.query = $scope.resetHighQueryParams($scope.query);
                $scope.getHighList();
            };
            $scope.getSimpleList = function () {
                $scope.queryType = 'simple';
                $scope.getList();
            };
            $scope.getHighList = function () {
                $scope.queryType = 'high';
                $scope.getList();
            };
            $scope.getList = function (pageIndex) {
                var isPageTrigger = typeof pageIndex !== 'undefined';
                pageIndex || (pageIndex = 1);
                $scope.query.page_index = pageIndex;
                $scope.query.proj_id = $scope.curProjectId;
                cstAssignService.getPublicList($scope.parseQueryParams($scope.query,$scope.queryType)).then(function (data) {
                    $scope.tableList = data;

                    // 分页触发时，继续选中标签
                    if($scope.checkCountAll && isPageTrigger){
                        _.map($scope.tableList.list,function(item){
                            item.checked = true;
                        });
                    }else{
                        $scope.checkAll = false;
                        $scope.checkCountAll = false;
                    }
                });
            };
            $scope.moveToRubbish = function (opp_ids) {
                var params = {
                    opp_ids: [].concat(opp_ids)
                };
                cstAssignService.moveToRubbish(params).then(function () {
                    $scope.getList();
                });
            };
            $scope.confirmMoveToRubbish = function () {
                if ($scope.hasCheck($scope.tableList.list)) {
                    util.confirm('确定要将选择的客户移到垃圾箱么？', {
                        ok: function () {
                            $scope.moveToRubbish(_.map($scope.getCheckList($scope.tableList.list), 'opp_id'));
                        }
                    });
                }
            };
            $scope.autoAssignPublic = function (total) {
                if(total === 0){
                    util.alert('没有可分配的客户');
                }else {
                    util.confirm('确定将查询到的' + total + '个客户全部分配吗？', {
                        ok: function () {
                            $scope.query.proj_id = $scope.curProjectId;
                            progressService.init('autoAssignPublic',$scope, $scope.parseQueryParams($scope.query,$scope.queryType), 4,
                                $scope.tableList.total,function(){
                                    $scope.getList();
                                },'自动分配');
                        }
                    });
                }
            };
            /* $scope方法 end */

            // init
            if ($scope.curProjectId) {
                $scope.getList();
            }
        }])
        .controller('rubbishCtrl', ['$scope', 'cstAssignService', function ($scope, cstAssignService) {
            /* 局部变量 start */

            /* 局部变量 end */

            /* $scope变量 start */
            $scope.loading = true;

            $scope.query = $scope.initQueryParams();

            /* $scope变量 end */

            /* $scope变量 watch start */
            $scope.$on('changeProjectId', function () {
                $scope.getList();
            });
            $scope.$on('checkChange', function (event, checkAll) {
                $scope.checkAll = checkAll;
            });
            /* $scope变量 watch end */


            /* $scope方法 start */
            $scope.resetGetList = function () {
                $scope.query = $scope.resetHighQueryParams($scope.query);
                $scope.getHighList();
            };
            $scope.getSimpleList = function () {
                $scope.queryType = 'simple';
                $scope.getList();
            };
            $scope.getHighList = function () {
                $scope.queryType = 'high';
                $scope.getList();
            };
            $scope.getList = function (pageIndex) {
                pageIndex || (pageIndex = 1);
                $scope.query.page_index = pageIndex;
                $scope.query.proj_id = $scope.curProjectId;
                cstAssignService.getRubbishList($scope.parseQueryParams($scope.query,$scope.queryType)).then(function (data) {
                    $scope.tableList = data;
                    $scope.checkAll = false;
                });
            };
            /* $scope方法 end */

            // init
            if ($scope.curProjectId) {
                $scope.getList();
            }
        }]);
});